package me.liuhui.mall.manager.web.config;

import me.liuhui.mall.manager.service.security.AdminPermissionFilter;
import me.liuhui.mall.manager.service.security.AuthenticationHandler;
import me.liuhui.mall.manager.service.security.KaptchaAuthenticationProvider;
import me.liuhui.mall.manager.service.security.Md5PasswordEncoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @author liuhui
 * prePostEnabled属性决定Spring Security在接口前注解是否可用@PreAuthorize,
 * @PostAuthorize等注解,设置为true,会拦截加了这些注解的接口
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {

    @Value("${security.superAdmin:SUPER_ADMIN}")
    private String superAdminRole;
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private AdminPermissionFilter adminPermissionFilter;
    @Resource
    private Md5PasswordEncoder md5PasswordEncoder;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        /* 开启跨域共享，  跨域伪造请求限制=无效 */
        http.cors().and().csrf().disable();

        // 授权配置
        http.authorizeRequests()
                .antMatchers("/", "/error", "/api/auth/*").permitAll()
                .antMatchers("/api/permission/*", "/api/role/*").hasRole(superAdminRole)
                .anyRequest().authenticated();


        /* 登录配置 */
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/api/auth/login")
                /* 登录失败后的处理 */
                .failureHandler(new AuthenticationHandler())
                /* 登录成功后的处理 */
                .successHandler(new AuthenticationHandler());

        /* 权限不足(没有赋予角色) 处理 */
        http.exceptionHandling().accessDeniedHandler(new AuthenticationHandler())
                //异常处理
                .authenticationEntryPoint(new AuthenticationHandler());

        //配置过滤器，动态修改当前权限
        http.addFilterBefore(adminPermissionFilter, UsernamePasswordAuthenticationFilter.class);
        // 配置登录页面
        http.formLogin().loginPage("/page/login.html").permitAll();

        /* 退出成功处理器 */
        http.logout().logoutUrl("/api/auth/logout").logoutSuccessHandler(new AuthenticationHandler()).invalidateHttpSession(true);
        //解决frame页面问题
        http.headers().frameOptions().sameOrigin();
        return http.build();
    }


    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        //配置静态文件不需要认证
        return (web) -> web.ignoring().antMatchers("/js/**", "/images/**", "/lib/**", "/css/**", "/page/login.html");
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        //验证码
        KaptchaAuthenticationProvider kaptchaAuthenticationProvider = new KaptchaAuthenticationProvider();
        kaptchaAuthenticationProvider.setUserDetailsService(userDetailsService);
        kaptchaAuthenticationProvider.setPasswordEncoder(md5PasswordEncoder);
        return kaptchaAuthenticationProvider;
    }


}

